import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _isUndefined from "lodash/isUndefined";
import _isNumber from "lodash/isNumber";
import _isEmpty from "lodash/isEmpty";

var _dec, _class;

/* eslint-disable no-nested-ternary */
import React, { PureComponent } from 'react';
import { Button, Col, Form, Input, Row, Spin, Select } from 'antd';
import pathParse from 'path-parse';
import Lov from 'components/Lov';
import TLEditor from 'components/TLEditor';
import { getCurrentOrganizationId, isTenantRoleLevel, getResponse } from 'utils/utils';
import { FORM_COL_2_LAYOUT, MODAL_FORM_ITEM_LAYOUT } from 'utils/constants';
import intl from 'utils/intl';
import { VERSION_IS_OP } from 'utils/config';
import { CODE_LOWER } from 'utils/regExp';
import Drawer from "../Drawer";
import styles from "./index.less?modules";
var FormItem = Form.Item;
var tenantRoleLevel = isTenantRoleLevel();
var Detail = (_dec = Form.create({
  fieldNameProp: null
}), _dec(_class = /*#__PURE__*/function (_PureComponent) {
  _inherits(Detail, _PureComponent);

  var _super = _createSuper(Detail);

  function Detail() {
    var _this;

    _classCallCheck(this, Detail);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      // dataSource: {},
      // roleTenantIsSame: false, // 选择所属租户后 租户id 和 角色的 租户一样
      roleLabels: []
    };
    return _this;
  }

  _createClass(Detail, [{
    key: "componentDidMount",
    value: // getSnapshotBeforeUpdate(prevProps) {
    //   const { visible, actionType, roleId, copyFormId, inheritFormId } = this.props;
    //   return (
    //     visible &&
    //     ((actionType === 'create' && isNumber(roleId) && roleId !== prevProps.roleId) ||
    //       (actionType === 'edit' && isNumber(roleId) && roleId !== prevProps.roleId) ||
    //       (actionType === 'copy' && isNumber(copyFormId) && copyFormId !== prevProps.copyFormId) ||
    //       (actionType === 'inherit' &&
    //         isNumber(inheritFormId) &&
    //         inheritFormId !== prevProps.inheritFormId))
    //   );
    // }
    //
    // componentDidUpdate(prevProps, prevState, snapshot) {
    // if (snapshot) {
    //   const { actionType } = this.props;
    //   // 只要是重新打开模态框 都需要查询一次 父级角色
    //   this.fetchAdminRole();
    //   if (actionType === 'edit') {
    //     this.handleFetchDataSource();
    //   }
    // }
    // }
    //
    // fetchAdminRole() {
    //   const { roleId, fetchAdminRole } = this.props;
    //   this.setState({
    //     parentRole: {},
    //   });
    //   fetchAdminRole(roleId).then(res => {
    //     if (res) {
    //       this.setState({
    //         parentRole: res,
    //       });
    //     }
    //   });
    // }
    //
    // handleFetchDataSource() {
    //   const { fetchDataSource = e => e, roleId, roleSourceCode } = this.props;
    //   fetchDataSource(roleId).then(res => {
    //     if (res) {
    //       this.setState({
    //         dataSource: {
    //           ...res,
    //           roleSourceMeaning: getCodeMeaning(res.roleSource || 'custom', roleSourceCode),
    //         },
    //       });
    //     }
    //   });
    // }
    // getCodeDescription(value, code = []) {
    //   let result;
    //   if (value && !isEmpty(code)) {
    //     const codeList = code.filter(n => n.value === value);
    //     if (!isEmpty(codeList)) {
    //       result = codeList[0].description;
    //     }
    //   }
    //   return result;
    // }
    function componentDidMount() {
      var _this2 = this;

      var _this$props = this.props,
          id = _this$props.currentRowData.id,
          actionType = _this$props.actionType;

      if (!_isUndefined(id) && actionType === 'edit') {
        this.props.queryLabel(id).then(function (res) {
          if (res && getResponse(res) && !_isEmpty(getResponse(res))) {
            _this2.setState({
              roleLabels: res
            });
          }
        });
      }
    }
  }, {
    key: "handleClose",
    value: function handleClose() {
      var _this$props$close = this.props.close,
          close = _this$props$close === void 0 ? function (e) {
        return e;
      } : _this$props$close;
      close();
    }
    /**
     * 编辑的保存
     */

  }, {
    key: "handleSave",
    value: function handleSave() {
      var _this3 = this;

      var _this$props2 = this.props,
          save = _this$props2.save,
          _this$props2$form$val = _this$props2.form.validateFields,
          validateFields = _this$props2$form$val === void 0 ? function (e) {
        return e;
      } : _this$props2$form$val,
          roleId = _this$props2.roleId,
          _this$props2$currentR = _this$props2.currentRowData,
          currentRowData = _this$props2$currentR === void 0 ? {} : _this$props2$currentR,
          _this$props2$labelLis = _this$props2.labelList,
          labelList = _this$props2$labelLis === void 0 ? [] : _this$props2$labelLis;
      validateFields(function (error, values) {
        if (!_isEmpty(error)) {
          return;
        }

        var description = values.description,
            name = values.name,
            tenantId = values.tenantId,
            _tls = values._tls,
            roleLabels = values.roleLabels;

        var data = _objectSpread(_objectSpread({}, currentRowData), {}, {
          description: description,
          name: name,
          _tls: _tls,
          roleLabels: labelList.filter(function (item) {
            return roleLabels.includes(item.name);
          }).map(function (item) {
            return _objectSpread(_objectSpread({}, item), {}, {
              labelId: item.id
            });
          }),
          tenantId: // eslint-disable-next-line no-nested-ternary
          VERSION_IS_OP && getCurrentOrganizationId() !== 0 ? getCurrentOrganizationId() : _isNumber(tenantId) ? tenantId : currentRowData.tenantId
        });

        save(roleId, data, _this3.handleClose.bind(_this3));
      });
    }
    /**
     * 创建角色/复制 继承的 保存
     */

  }, {
    key: "handleCreate",
    value: function handleCreate() {
      var _this4 = this;

      var _this$props3 = this.props,
          actionType = _this$props3.actionType,
          create = _this$props3.create,
          _this$props3$form$val = _this$props3.form.validateFields,
          validateFields = _this$props3$form$val === void 0 ? function (e) {
        return e;
      } : _this$props3$form$val,
          inheritFormId = _this$props3.inheritFormId,
          copyFormId = _this$props3.copyFormId,
          inherit = _this$props3.inherit,
          copy = _this$props3.copy,
          _this$props3$currentR = _this$props3.currentRowData,
          currentRowData = _this$props3$currentR === void 0 ? {} : _this$props3$currentR,
          _this$props3$labelLis = _this$props3.labelList,
          labelList = _this$props3$labelLis === void 0 ? [] : _this$props3$labelLis;
      var parentRoleId = currentRowData.adminFlag === 1 ? currentRowData.id : currentRowData.adminRoleId;
      validateFields(function (error, values) {
        if (!_isEmpty(error)) {
          return;
        }

        var code = values.code,
            description = values.description,
            name = values.name,
            tenantId = values.tenantId,
            _tls = values._tls,
            roleLabels = values.roleLabels;
        var data = {
          code: code,
          description: description,
          name: name,
          tenantId: VERSION_IS_OP && getCurrentOrganizationId() !== 0 ? getCurrentOrganizationId() : tenantId,
          parentRoleId: parentRoleId,
          _tls: _tls,
          roleLabels: labelList.filter(function (item) {
            return roleLabels.includes(item.name);
          }).map(function (item) {
            return _objectSpread(_objectSpread({}, item), {}, {
              labelId: item.id
            });
          }),
          roleSource: 'custom',
          rolePermissionSets: []
        };

        if (actionType === 'inherit') {
          data.inheritRoleId = inheritFormId;
          inherit(data, _this4.handleClose.bind(_this4));
        }

        if (actionType === 'copy') {
          data.copyFromRoleId = copyFormId;
          copy(data, _this4.handleClose.bind(_this4));
        }

        if (actionType === 'create') {
          create(data, _this4.handleClose.bind(_this4));
        }
      });
    } // handleDeselect(value) {
    //   // const { roleLabels = [] } = this.state;
    //   // if (!isEmpty(roleLabels)) {
    //   //   const temp = roleLabels.filter((item) => item.label.name === value);
    //   //   if (temp[0] && temp[0].assignType === 'A') {
    //   //     const roleLabel = this.props.form.getFieldValue('roleLabels');
    //   //     setTimeout(() => {
    //   //       this.props.form.setFieldsValue({
    //   //         roleLabels: roleLabel,
    //   //       });
    //   //     }, 0);
    //   //   }
    //   // }
    // }

  }, {
    key: "render",
    value: function render() {
      var _this$props4 = this.props,
          actionType = _this$props4.actionType,
          getFieldDecorator = _this$props4.form.getFieldDecorator,
          _this$props4$processi = _this$props4.processing,
          processing = _this$props4$processi === void 0 ? {} : _this$props4$processi,
          visible = _this$props4.visible,
          _this$props4$currentR = _this$props4.currentRowData,
          currentRowData = _this$props4$currentR === void 0 ? {} : _this$props4$currentR,
          _this$props4$labelLis = _this$props4.labelList,
          labelList = _this$props4$labelLis === void 0 ? [] : _this$props4$labelLis,
          isHaveParams = _this$props4.isHaveParams;
      var name = currentRowData.name,
          viewCode = currentRowData.viewCode,
          description = currentRowData.description,
          tenantId = currentRowData.tenantId,
          tenantName = currentRowData.tenantName,
          _token = currentRowData._token,
          levelPath = currentRowData.levelPath,
          _levelPath = currentRowData._levelPath;
      var _this$state$roleLabel = this.state.roleLabels,
          roleLabels = _this$state$roleLabel === void 0 ? [] : _this$state$roleLabel;
      var drawerTitle = {
        edit: intl.get('ciam.roleManagement.view.title.content.editRole', {
          name: name
        }).d("\u4FEE\u6539\u201C".concat(name, "\u201D")),
        copy: intl.get("ciam.roleManagement.view.title.createRole").d('创建角色'),
        inherit: intl.get("ciam.roleManagement.view.title.createRole").d('创建角色'),
        create: intl.get("ciam.roleManagement.view.title.createRole").d('创建角色')
      };
      var parentRoleName = // eslint-disable-next-line no-nested-ternary
      actionType === 'edit' ? currentRowData.parentRoleName : currentRowData.name; // 在 新建/继承/复制 情况下的禁用
      // eslint-disable-next-line no-nested-ternary

      var tenantDisabled = !(actionType === 'inherit' ? currentRowData.level === 'organization' && currentRowData.tenantId === 0 : currentRowData.adminFlag === 1 ? currentRowData.level === 'organization' && currentRowData.tenantId === 0 : currentRowData.adminRoleLevel === 'organization' && currentRowData.adminRoleTenantId === 0);
      var drawerProps = {
        title: drawerTitle[actionType],
        visible: visible,
        onCancel: this.handleClose.bind(this),
        width: 1000,
        anchor: 'right',
        wrapClassName: styles['ciam-role-detail'],
        footer: /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
          onClick: this.handleClose.bind(this),
          disabled: processing.save || processing.create || false
        }, intl.get("cpaas.common.button.cancel").d('取消')), (actionType === 'create' || actionType === 'copy' || actionType === 'inherit') && /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          loading: processing.create || processing.copy || processing.inherit,
          onClick: this.handleCreate.bind(this)
        }, intl.get("cpaas.common.button.ok").d('确定')), actionType === 'edit' && /*#__PURE__*/React.createElement(Button, {
          type: "primary",
          loading: processing.save,
          onClick: this.handleSave.bind(this)
        }, intl.get("cpaas.common.button.ok").d('确定')))
      };
      return /*#__PURE__*/React.createElement(Drawer, drawerProps, /*#__PURE__*/React.createElement(Spin, {
        spinning: processing.query || processing.queryParentRole || false
      }, /*#__PURE__*/React.createElement(Form, {
        className: styles['ciam-role-detail-form']
      }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, FORM_COL_2_LAYOUT, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('ciam.roleManagement.model.roleManagement.adminRole').d('父级管理角色')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('parentRoleName', {
        initialValue: parentRoleName
      })( /*#__PURE__*/React.createElement(Input, {
        disabled: true
      })))), /*#__PURE__*/React.createElement(Col, FORM_COL_2_LAYOUT, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get("ciam.roleManagement.model.roleManagement.inheritedRole").d('继承自')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('inheritedRoleName', {
        initialValue: // eslint-disable-next-line no-nested-ternary
        actionType === 'inherit' ? currentRowData.name : actionType === 'edit' ? currentRowData.inheritedRoleName : undefined
      })( /*#__PURE__*/React.createElement(Input, {
        disabled: true
      }))))), /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, FORM_COL_2_LAYOUT, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('ciam.roleManagement.model.roleManagement.code').d('角色编码')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('code', {
        initialValue: actionType === 'edit' ? pathParse(viewCode || '').base : undefined,
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get('ciam.roleManagement.model.roleManagement.code').d('角色编码')
          })
        }, {
          max: 64,
          message: intl.get("cpaas.common.validation.max", {
            max: 64
          })
        }, {
          pattern: CODE_LOWER,
          message: intl.get('cpaas.common.validation.codeLower').d('全小写及数字，必须以字母、数字开头，可包含“-”、“_”、“.”、“/”')
        }]
      })( /*#__PURE__*/React.createElement(Input, {
        trim: true,
        typeCase: "lower",
        inputChinese: false,
        disabled: actionType === 'edit'
      })))), /*#__PURE__*/React.createElement(Col, FORM_COL_2_LAYOUT, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get("ciam.roleManagement.model.roleManagement.name").d('角色名称')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('name', {
        initialValue: actionType === 'edit' ? name : undefined,
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get("ciam.roleManagement.model.roleManagement.name").d('角色名称')
          })
        }, {
          max: 64,
          message: intl.get("cpaas.common.validation.max", {
            max: 64
          })
        }]
      })( /*#__PURE__*/React.createElement(TLEditor, {
        label: intl.get('ciam.roleManagement.view.title.name').d('角色名称'),
        field: "name",
        inputSize: {
          zh: 64,
          en: 64
        } // eslint-disable-next-line
        ,
        token: actionType === 'create' || actionType === 'copy' ? undefined : _token
      }))))), /*#__PURE__*/React.createElement(Row, null, actionType !== 'create' && /*#__PURE__*/React.createElement(Col, {
        span: 12
      }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('ciam.roleManagement.model.roleManagement.levelPath').d('角色路径')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('levelPath', {
        initialValue: actionType === 'edit' ? isHaveParams ? _levelPath : levelPath : undefined
      })( /*#__PURE__*/React.createElement(Input, {
        disabled: true
      })))), !VERSION_IS_OP && /*#__PURE__*/React.createElement(Col, {
        span: 12
      }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('ciam.roleManagement.model.roleManagement.tenant').d('所属租户')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('tenantId', {
        initialValue: actionType === 'edit' ? tenantId : tenantDisabled ? actionType === 'inherit' ? currentRowData.tenantId : // 新建/复制
        (actionType === 'create' || actionType === 'copy') && currentRowData.adminFlag === 1 ? currentRowData.tenantId : currentRowData.adminRoleTenantId : undefined,
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get('ciam.roleManagement.model.roleManagement.tenant').d('所属租户')
          })
        }]
      })( /*#__PURE__*/React.createElement(Lov, {
        disabled: actionType === 'edit' || tenantDisabled,
        textValue: actionType === 'edit' ? tenantName : tenantDisabled ? actionType === 'inherit' ? currentRowData.tenantName : // 新建/复制
        (actionType === 'create' || actionType === 'copy') && currentRowData.adminFlag === 1 ? currentRowData.tenantName : currentRowData.adminRoleTenantName : undefined,
        code: tenantRoleLevel ? 'CPFM.TENANT.ORG' : 'CPFM.TENANT'
      })))), (actionType === 'create' || VERSION_IS_OP) && /*#__PURE__*/React.createElement(Col, {
        span: 12
      }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('ciam.roleManagement.model.roleManagement.description').d('角色描述')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('description', {
        initialValue: actionType === 'edit' ? description : undefined,
        rules: [{
          max: 240,
          message: intl.get('cpaas.common.validation.max', {
            max: 240
          })
        }]
      })( /*#__PURE__*/React.createElement(Input, null)))), actionType === 'create' && VERSION_IS_OP && /*#__PURE__*/React.createElement(Col, FORM_COL_2_LAYOUT, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('ciam.roleManagement.model.roleManagement.roleLabels').d('角色标签')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('roleLabels', {
        initialValue: roleLabels.filter(function (i) {
          return i.label;
        }).map(function (item) {
          return item.label && item.label.name;
        }) || []
      })( /*#__PURE__*/React.createElement(Select, {
        mode: "multiple"
      }, labelList.map(function (n) {
        return /*#__PURE__*/React.createElement(Select.Option, {
          key: n.name,
          value: n.name,
          disabled: roleLabels.filter(function (item) {
            return item.assignType === 'A';
          }).map(function (item) {
            return item.label && item.label.name;
          }).includes(n.name)
        }, n.name);
      })))))), /*#__PURE__*/React.createElement(Row, null, actionType !== 'create' && !VERSION_IS_OP && /*#__PURE__*/React.createElement(Col, {
        span: 12
      }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('ciam.roleManagement.model.roleManagement.description').d('角色描述')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('description', {
        initialValue: actionType === 'edit' ? description : undefined,
        rules: [{
          max: 240,
          message: intl.get('cpaas.common.validation.max', {
            max: 240
          })
        }]
      })( /*#__PURE__*/React.createElement(Input, null)))), (actionType !== 'create' ? true : !VERSION_IS_OP) && /*#__PURE__*/React.createElement(Col, FORM_COL_2_LAYOUT, /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('ciam.roleManagement.model.roleManagement.roleLabels').d('角色标签')
      }, MODAL_FORM_ITEM_LAYOUT), getFieldDecorator('roleLabels', {
        initialValue: roleLabels.filter(function (i) {
          return i.label;
        }).map(function (item) {
          return item.label && item.label.name;
        }) || []
      })( /*#__PURE__*/React.createElement(Select, {
        mode: "multiple"
      }, labelList.map(function (n) {
        return /*#__PURE__*/React.createElement(Select.Option, {
          key: n.name,
          value: n.name,
          disabled: roleLabels.filter(function (item) {
            return item.assignType === 'A';
          }).map(function (item) {
            return item.label && item.label.name;
          }).includes(n.name)
        }, n.name);
      })))))))));
    }
  }]);

  return Detail;
}(PureComponent)) || _class);
export { Detail as default };